<?php

	//�� ����� ������������ �������� ����� ������
	abstract class ModelObject {
		protected $modelName = 'Model';
		protected $id = 0;
		protected $created = null;
		

		function __construct($id=null) {
        	$this->id = intval($id);
		}

		public function Id() {
			return $this->id;
		}

		public function AsSource($otherName = false) {
			$name = $otherName?$otherName:$this->name;
			$res = new XmlSource($name);
			$res->Attribute('id', $this->id);
			if($this->created)
				$date = CutDate($this->created);
				$res->Attribute('created', $date);

			return $res;
		}

		public function Load() {
			if($this->id<1) throw new Exception("Can't load object because it's id isn't defined");
			$query = sprintf("SELECT `created` FROM `Object` WHERE `id`=%d", intval($this->id));
			$res = mysql_query($query);
			if($res) {
				$row = mysql_fetch_assoc($res);
				$this->created = $row['created'];
			}else{
				throw new Exception("Can't load object with SQL error!");
			}
		}

		public static function Install() {
			if(ModelObject::TableIsExists('Object')) return;
			$query = sprintf("
					CREATE TABLE `Object` (
					  `id`			int(32) unsigned NOT NULL auto_increment,
					  `created`		datetime NOT NULL default '0000-00-00 00:00:00',
					  `Type`		int(32) unsigned NOT NULL,
					  PRIMARY KEY	(`id`),
					  FOREIGN KEY	(`Type`) REFERENCES `ObjectType`(`id`) ON DELETE CASCADE
					) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8
				");
			mysql_query($query);

			echo "ModelObject installed\n";
		}

		final protected static function ModelId($modelName) {
			$query = sprintf("SELECT `id` FROM `ObjectType` WHERE `name`='%s'", mes($modelName));
			$res = mysql_query($query);
			if(!$res) throw new Exception("Problems here ".__FILE__.":".__LINE__);
			$row = mysql_fetch_assoc($res);
			return intval($row['id']);
		}

		final protected static function TableIsExists($tableName) {
			if(!$tableName) return false;
            $query = sprintf("DESCRIBE `%s`", $tableName);
            return (bool)mysql_query($query);
		}

		protected function RegisterObject() {
			if($this->id > 0) throw new Exception("Object already registered!");
			$query = sprintf("
				INSERT INTO `Object` (
						`created`,
						`Type`)
					VALUES( NOW(), %d)", ModelObject::ModelId($this->modelName));
			mysql_query($query);
			$this->id = mysql_insert_id();
			//echo $this->id."\n";
			return $this->id;
		}

		public function Save() {
			if($this->id < 1) $this->RegisterObject();
		}

		public function Remove() {
			if($this->id<1) return;
			$query = sprintf("DELETE FROM `Object` WHERE `id`=%d", $this->id);
			mysql_query($query);
			$this->id = 0;
		}
	}
?>